package com.simon.hse.activity.danger;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.DangerStopInput;
import com.simon.hse.http.entity.DangerStopOutput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.TrainPersonOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;

/**
 * STOP安全沟通卡
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_danger_stop)
public class DangerStopActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.iv_common_right)
    ImageView mIv_common_right;

    @ViewInject(R.id.ll_danger_stop_person)
    LinearLayout mLl_danger_stop_person;

    @ViewInject(R.id.tv_danger_stop_person)
    TextView mTv_danger_stop_person;

    @ViewInject(R.id.tv_danger_stop_date)
    TextView mTv_danger_stop_date;

    @ViewInject(R.id.ll_danger_stop_day)
    LinearLayout mLl_danger_stop_day;

    @ViewInject(R.id.tv_danger_stop_day)
    TextView mTv_danger_stop_day;

    @ViewInject(R.id.ll_danger_stop_area)
    LinearLayout mLl_danger_stop_area;

    @ViewInject(R.id.tv_danger_stop_area)
    TextView mTv_danger_stop_area;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<DangerStopOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// STOP安全沟通卡列表
    private List<TrainPersonOutput.DataBean.PageDataBean> mListTrainPerson = new ArrayList<>();// 观察人
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerDaysList = new ArrayList<>();// 班次
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerAreasList = new ArrayList<>();// 区域
    private String observerId;// 观察人
    private String dayId;// 观察人
    private String areaId;// 观察人

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("STOP安全沟通卡");
        mIv_common_right.setImageResource(R.mipmap.tab_add_icon);

        initRecyclerView();
        initObserver();
        initDaysAndAreas();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.iv_common_right
            , R.id.ll_danger_stop_person, R.id.ll_danger_stop_date, R.id.ll_danger_stop_day, R.id.ll_danger_stop_area})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.iv_common_right:
                Intent intent = new Intent(DangerStopActivity.this, DangerStopDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_danger_stop_person:
                initObserverPop();
                break;
            case R.id.ll_danger_stop_date:
                publishDate();
                break;
            case R.id.ll_danger_stop_day:
                initDaysPop();
                break;
            case R.id.ll_danger_stop_area:
                initAreasPop();
                break;
        }
    }

    private void initRecyclerView() {
        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage*10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(DangerStopActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(DangerStopActivity.this, R.layout.layout_item_danger_stop, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DangerStopOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DangerStopOutput.DataBean.PageDataBean dataBean) {
                TextView tv_danger_stop_title = holder.getView(R.id.tv_danger_stop_title);
                TextView tv_danger_stop_day = holder.getView(R.id.tv_danger_stop_day);

                String observaDate = dataBean.getObservaDate();
                if (!TextUtils.isEmpty(observaDate)) {
                    String[] split = observaDate.split(" ");
                    String ymd = split[0];
                    String[] split1 = ymd.split("-");
                    observaDate = split1[0] + split1[1] + split1[2];
                }
                tv_danger_stop_title.setText(observaDate + dataBean.getObservePeopleText());
                switch (dataBean.getShifts()) {
                    case "0":
                        tv_danger_stop_day.setText("白班");
                        break;
                    case "1":
                        tv_danger_stop_day.setText("中班");
                        break;
                    case "2":
                        tv_danger_stop_day.setText("晚班");
                        tv_danger_stop_day.setTextColor(R.color.home_font);
                        break;
                }

            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                Intent intent = new Intent(DangerStopActivity.this, DangerStopDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("ID",mDataBeanList.get(position).getId());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    /**
     * 观察人
     */
    private void initObserver() {
        TrainPersonOutput.DataBean.PageDataBean pageDataBean = new TrainPersonOutput.DataBean.PageDataBean();
        pageDataBean.setName("全部");
        pageDataBean.setId("");
        mListTrainPerson.add(pageDataBean);
        mListTrainPerson.addAll(MyApplication.getInstance().mListTrainPerson);
    }

    /**
     * 班次 区域
     */
    private void initDaysAndAreas() {
        DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = new DropDownOutput.DataBean.DataDicListBean.ValueBean();
        valueBean.setValue("全部");
        valueBean.setKey("");
        mDangerDaysList.add(valueBean);
        mDangerDaysList.addAll(MyApplication.getInstance().mDangerDaysList);

        mDangerAreasList.add(valueBean);
        mDangerAreasList.addAll(MyApplication.getInstance().mDangerAreasList);
    }

    private void initData() {
        DangerStopInput dangerStopInput = new DangerStopInput();
        DangerStopInput.ModelBean modelBean = new DangerStopInput.ModelBean();
        modelBean.setObservaDate("");
        if (!TextUtils.isEmpty(observerId)) {
            modelBean.setObservePeople(observerId);
        }
        if (!TextUtils.isEmpty(areaId)) {
            modelBean.setSituation(areaId);
        }
        if (!TextUtils.isEmpty(dayId)) {
            modelBean.setShifts(dayId);
        }

        dangerStopInput.setModel(modelBean);
        dangerStopInput.setLimit(10);
        dangerStopInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().DANGER_STOP_LIST(HttpManager.getInstance().requestBody(dangerStopInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DangerStopOutput dangerStopOutput = new Gson().fromJson(result, DangerStopOutput.class);
                if (dangerStopOutput.getResult().equals("Success")) {
                    totalPage = dangerStopOutput.getData().getRowCount();
                    List<DangerStopOutput.DataBean.PageDataBean> dataBeanList = dangerStopOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dangerStopOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 观察人-pop
     */
    private void initObserverPop() {
        View inflate = LayoutInflater.from(DangerStopActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerStopActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerStopActivity.this, R.layout.layout_item_common_more_department, mListTrainPerson);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainPersonOutput.DataBean.PageDataBean pageDataBean = mListTrainPerson.get(position);
                observerId = pageDataBean.getId();
                mTv_danger_stop_person.setText(pageDataBean.getName());
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerStopActivity.this, inflate, mLl_danger_stop_person);
    }

    /**
     * 观察日期
     */
    private void publishDate() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = DateTimeUtils.getCurrentYMD();
        String[] split = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        endDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(DangerStopActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
                mTv_danger_stop_date.setText(sdf_ymd.format(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }

    /**
     * 班次-pop
     */
    private void initDaysPop() {
        View inflate = LayoutInflater.from(DangerStopActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerStopActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerStopActivity.this, R.layout.layout_item_common_more_department, mDangerDaysList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mDangerDaysList.get(position);
                dayId = valueBean.getKey();
                mTv_danger_stop_day.setText(valueBean.getValue());
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerStopActivity.this, inflate, mLl_danger_stop_day);
    }

    /**
     * 区域-pop
     */
    private void initAreasPop() {
        View inflate = LayoutInflater.from(DangerStopActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerStopActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerStopActivity.this, R.layout.layout_item_common_more_department, mDangerAreasList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mDangerAreasList.get(position);
                areaId = valueBean.getKey();
                mTv_danger_stop_area.setText(valueBean.getValue());
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerStopActivity.this, inflate, mLl_danger_stop_area);
    }
    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
